import React, { useEffect, useState } from 'react'
import { Form, Button, DatePicker, Input, Modal, Radio, Select, Steps, Row, Col, TreeSelect } from 'antd'
import { socialTraineeStateArray,websiteList } from '@/utils/constant'
import { isNewOrReinstate, getJobByOrgId} from '../../service'
import { findItemByTree } from '@/utils/functions';

import moment from 'moment'
import { connect } from 'umi'

const FormItem = Form.Item
const { Step } = Steps
const { TextArea } = Input
const { Option } = Select
const RadioGroup = Radio.Group

const formLayout = {
  labelCol: { span: 7 },
}

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
}

const CreateForm = (props) => {

  const { visible, onSubmit, onCancel, currentUser, recruitment = {} } = props
  const { options = {} } = recruitment
  const { orgTree = [], orgLine = [], orgSystem = [], jobLevel = [] } = options

  const [form] = Form.useForm()
  useEffect(() => {
    setManagementJobLevel([{ id: '', name: '无' }, ...jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK')])
    setProfessionJobLevel([{ id: '', name: '无' }, ...jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK')])
  }, [jobLevel])

  const [formVals, setFormVals] = useState({
    socialTrainee: '0',
    principal: currentUser.name,
    id: props.values.id,
  })

  const [currentStep, setCurrentStep] = useState(0)
  const [searchText, setSearchText] = useState('')
  const [searchInfo, setSearchInfo] = useState({})
  const [searchLoading, setSearchLoading] = useState(false)
  const [unitTree, setUnitTree] = useState([])
  const [jobList, setJobList] = useState([])
  const [managementJobLevel, setManagementJobLevel] = useState([])
  const [professionJobLevel, setProfessionJobLevel] = useState([])

  const search = async () => {
    const fieldsValue = await form.validateFields()
    const { idCard } = fieldsValue
    setSearchLoading(true)
    isNewOrReinstate(idCard).then((res) => {
      setSearchLoading(false)
      if (res) {
        if (['3', '4', '5', '6'].indexOf(res.employeestatus) > -1) {
          //离职员工
          const years = moment().diff(moment(res.hiredate), 'years')
          if (years >= 1) {
            setSearchText(`工号${res.code}，姓名${res.name}，入职日期${res.hiredate}，离职日期${res.dimissiondate}，离职周期超过一年`)
          } else {
            setSearchText(`工号${res.code}，姓名${res.name}，入职日期${res.hiredate}，离职日期${res.dimissiondate}，离职周期不到一年`)
            setSearchInfo(res)
            return
          }
        } else {
          // 在职员工
          setSearchText(`工号${res.code}，姓名${res.name}，入职日期${res.hiredate}，目前此员工在职`)
        }
      } else {
        setSearchText('无此员工信息')
      }
      setSearchInfo({})
    })
  }

  const onFormCancel = () => {
    form.resetFields()
    onCancel()
    setCurrentStep(0)
  }

  const forward = async () => {
    const fieldsValue = await form.validateFields()
    const { socialTrainee } = fieldsValue
    if (currentStep === 0 && socialTrainee === '1') {
      setCurrentStep(currentStep + 2)
    } else {
      if (currentStep === 1 && searchInfo.name) {
        //离职不到一年复职
      }
      setCurrentStep(currentStep + 1)
    }
  }

  const backward = () => setCurrentStep(currentStep - 1)

  const handleNext = async () => {
    const fieldsValue = await form.validateFields()

    setFormVals({ ...formVals, ...fieldsValue })
    if (currentStep < 2) {
      await forward()
    } else {
      form.resetFields()
      onSubmit(fieldsValue)
    }
  }

  const onChangeUnitId = (e) => {
    getJobByOrgId(e).then((res) => {
      setJobList(res)
    })
  }

  const onChangeOrgId = (e) => {
    const item = findItemByTree(orgTree, e)
    setUnitTree(item ? item.children : [])
  }

  const filterOption = (input, option) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
  }

  const renderContent = () => {
    if (currentStep === 1) {
      return (
        <>
          <Form.Item label="身份证号:" extra={searchText ? '' : '请输入身份证查询此员工是否曾经入职过'}>
            <Row gutter={10}>
              <Col span={16}>
                <Form.Item name="idCard" noStyle rules={[{ required: true, message: '请输入身份证号进行查询' }]}>
                  <Input/>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Button onClick={search} loading={searchLoading}>搜索</Button>
              </Col>
            </Row>
            <Row gutter={10}>
              <div style={{ padding: '12px 4px', fontSize: '14px' }}>{searchText}</div>
            </Row>
          </Form.Item>
        </>
      )
    }
    if (currentStep === 2) {
      return (
        <>
          <Row gutter={24}>
            <Col {...colStyle}>
              <FormItem name="principal" label="招聘负责人">
                <Input/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="orgId" label="公司">
                <TreeSelect treeData={orgTree} onChange={onChangeOrgId}/>
              </FormItem>
            </Col>
            <Col {...colStyle}>
              <FormItem name="unitId" label="部门">
                <TreeSelect treeData={unitTree} onChange={onChangeUnitId}/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="jobId" label="职位">
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {jobList.map((item, index) => {
                    return (
                      <Option value={`${item.jobId}`} key={item.jobId}>
                        {item.jobName}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="name" label="姓名">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="privatemail" label="个人电子邮箱">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="mobile" label="手机">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="idcard" label="身份证">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="hiredate" label="拟入职日期">
                <DatePicker/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="managementJoblevelId" label="管理职级">
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {managementJobLevel.map((item, index) => {
                    return (
                      <Option value={`${item.id}`} key={item.id}>
                        {item.name}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="professionJoblevelId" label="专业职级">
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {professionJobLevel.map((item, index) => {
                    return (
                      <Option value={`${item.id}`} key={item.id}>
                        {item.name}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="socialTrainee" label="招聘类型">
                <Select placeholder="请选择" disabled>
                  {socialTraineeStateArray.map((item, index) => {
                    return (
                      <Option value={`${index}`} key={index}>
                        {item}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="channel" label="招聘渠道">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="recruitmentWeb" label="招聘网站">
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {
                    websiteList.map((item, index) => {
                      return (
                        <Option value={item.value} key={item.value}>
                          {item.label}
                        </Option>
                      )
                    })
                  }
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="innerReferrer" label="推荐人（内部）">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="outerReferrer" label="推荐人（外部）">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="probationday" label="试用期" rules={[{required: true, message: '试用期不能为空'}]}>
                <Input type='number'/>
              </FormItem>
            </Col>


            <Col {...colStyle}>
              <FormItem name="performance" label="模块工资">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="monthlySalary" label="基本工资">
                <Input/>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="jobSystemId" label="体系">
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {orgSystem.map((item, index) => {
                    return (
                      <Option value={`${item.id}`} key={item.id}>
                        {item.name}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

            <Col {...colStyle}>
              <FormItem name="lineId" label="条线">
                <Select placeholder="请选择" showSearch filterOption={filterOption}>
                  {orgLine.map((item, index) => {
                    return (
                      <Option value={`${item.id}`} key={item.id}>
                        {item.name}
                      </Option>
                    )
                  })}
                </Select>
              </FormItem>
            </Col>

          </Row>
        </>
      )
    }
    return (
      <>
        <FormItem name="socialTrainee" label="招聘类型">
          <RadioGroup>
            {
              socialTraineeStateArray.map((item, index) => {
                return <Radio value={`${index}`} key={index}>{item}</Radio>
              })
            }
          </RadioGroup>
        </FormItem>
      </>
    )
  }

  const renderFooter = () => {
    if (currentStep === 1) {
      return (
        <>
          <Button style={{ float: 'left' }} onClick={backward}>
            上一步
          </Button>
          <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            下一步
          </Button>
        </>
      )
    }
    if (currentStep === 2) {
      return (
        <>
          <Button style={{ float: 'left' }} onClick={backward}>
            上一步
          </Button>
          <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleNext()}>
            完成
          </Button>
        </>
      )
    }
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleNext()}>
          下一步
        </Button>
      </>
    )
  }

  return (
    <Modal
      width={1280}
      destroyOnClose
      title="新建"
      visible={visible}
      footer={renderFooter()}
      onOk={handleNext}
      onCancel={() => onCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Steps style={{ marginBottom: 28, padding: '0 290px' }} current={currentStep}>
        <Step title="招聘类型"/>
        <Step title="信息检索"/>
        <Step title="基础信息"/>
      </Steps>
      <Form
        {...formLayout}
        form={form}
        initialValues={{
          socialTrainee: formVals.socialTrainee,
          principal: formVals.principal,
          id: formVals.id,
        }}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

// export default CreateForm

export default connect(({ user, recruitment }) => ({
  recruitment,
  currentUser: user.currentUser,
}))(CreateForm)
